package com.yh.service.impl;

import com.yh.NotFoundException;
import com.yh.dao.TagReposiory;
import com.yh.po.Tag;
import com.yh.po.Type;
import com.yh.service.TagService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagReposiory tagReposiory;

    @Transactional//添加事务控制
    @Override
    public Tag saveTag(Tag tag) {
        return tagReposiory.save(tag);
    }

    @Transactional//添加事务控制
    @Override
    public Tag getTagByName(String name) {
        return tagReposiory.findByName(name);
    }

    @Transactional//添加事务控制
    @Override
    public Tag getTag(Long id) {

        Optional<Tag> tag = tagReposiory.findById(id);

        return tag.get();
    }

    @Transactional//添加事务控制
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagReposiory.findAll(pageable);
    }

    @Override
    public List<Tag> listTag() {
        return tagReposiory.findAll();
    }

    @Override
    public List<Tag> listTagTop() {
        List<Tag> all = tagReposiory.findAll();
        Collections.sort(all, new Comparator<Tag>() {
            @Override
            public int compare(Tag o1, Tag o2) {
                int i = o2.getBlogs().size() - o1.getBlogs().size();
                if(i == 0){
                    return o2.getBlogs().size() - o1.getBlogs().size();
                }
                return i;
            }
        });
        return all;
    }

    @Override
    public List<Tag> listTag(String ids) {
        return tagReposiory.findAllById(converToList(ids));
    }

    private List<Long> converToList(String ids){
        List<Long> list = new ArrayList<>();
        if(!"".equals(ids) && ids != null){
            String[] idarray = ids.split(",");
            for(int i = 0; i < idarray.length; i++){
                list.add(new Long(idarray[i]));
            }
        }
        return list;
    }

    @Transactional//添加事务控制
    @Override
    public Tag updateTag(Long id, Tag tag) {

        Optional<Tag> t = tagReposiory.findById(id);

        if (t == null) {
            throw new NotFoundException("不存在该类型！");
        }

        BeanUtils.copyProperties(tag,t.get());

        return tagReposiory.save(t.get());
    }

    @Transactional//添加事务控制
    @Override
    public void deleteTag(Long id) {
        tagReposiory.deleteById(id);
    }
}
